package com.briup.corejava.day21;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP协议下的服务器
 */
public class TcpServer {
    public static void main(String[] args) {
        // 创建ServerSocket对象，监听一个端口
        ServerSocket serverSocket = null;
        // 创建Socket对象，用于接收
        Socket socket = null;
        // 定义端口号
        int port = 8888;
        try {
            serverSocket = new ServerSocket(port);
            // 开启监听
            System.out.println("服务器启动，正在监听["+port+"]端口");
            socket = serverSocket.accept();
            System.out.println("接收成功 socket = " + socket);
            // 从socket中读出数据
            InputStream inputStream = socket.getInputStream();
            // 只读一次
            byte[] buf = new byte[1024];
            int len = inputStream.read(buf);
            System.out.println(new String(buf,0,len));

            // 和客户端对话，返回一个消息
            OutputStream outputStream = socket.getOutputStream();
            PrintStream ps = new PrintStream(outputStream);
            ps.println("客户端你好，我在，你要干嘛？");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
